package com.sundog.sundroid;

import java.util.Map;
import java.util.Scanner;

import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;

import com.sundog.sundroid.google.GoogleService;
import com.sundog.sundroid.testclasses.AdminSimulator;

/**
 * Screen for the admin to choose a story
 * 
 * @author Matt
 *
 */
public class scrumMaster extends ListActivity implements OnClickListener {
	
	/** Spreadsheet ID */
	public static String id = "";
	/** Story names array */
	public static String [] storyNames;
	/** Story details array */
	public static String [] detailed;
	/** Story ID array */
	public static String [] storyID;
	/** User name array */
	public static String [] userNames;
	/** User name map */
	public static Map<String, String> users;
	/** User online status array */
	public static String [] userOnlineStatus;
	/** Story map */
	public static Map<String, String> storys;
	/** Current story ID */
	public static String storyId;
	/** Current story ID */
	public static int stid;
	/** Story details map */
	public static Map<String, String> details;
	/** Flag for checking story list */
	public static int check = 0;
	/** Instance of this class */
	public scrumMaster  scrum = this;
	/** Boolean for executing thread */
	public static boolean execute = true;
	/** User who sent a message  */
	public String User;
	/** Boolean for detecting received messages */
	public boolean messageReceived;
	/** Connection configuration for XMPP messaging */
	private final ConnectionConfiguration connConfig = new ConnectionConfiguration("talk.google.com", 80, "jabber.org"); 
	/** Establishes XMPP connection using the connection configuration */
	public final XMPPConnection connection = new XMPPConnection(connConfig);
	/** Create a packet filter to respond to messages from a single user */
	PacketFilter filter = new PacketTypeFilter(Message.class);

	/** Create a packet listener to process received packets */
	PacketListener myListener = new PacketListener() {

		/** Method for processing messages */
		public void processPacket(Packet packet) {
			Message msg = (Message) packet;

			Log.d("***", "Admin received message: " + msg.getBody() + " from " + msg.getFrom());
			User = msg.getFrom();
			setUserStatus();  // set the status of current user to online.
		    
			// Create a scanner and parse the user name from the message 
			Scanner in = new Scanner(msg.getFrom());
			in.useDelimiter("/");
			String user = in.next();
			
			// Reply to received message
			Log.d("***", "checking getfrom " + User);
			Message mess = new Message();
			mess.setTo(user);
			mess.setType(Message.Type.headline);
			mess.setBody("Admin received user message");
			connection.sendPacket(mess);
			Log.d("***", "Admin sent message " + mess.getBody());
			messageReceived = true;
	}};

@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.modscreen);
		
		// Connect to XMPP server
        connectToServer();
		
		String user[] = Login.usersNames;//this.getIntent().getStringArrayExtra("userList");
		Log.d("USERINSCRUM", user[0]);
		
		// Initialize variables
		users = GoogleService.returnUserList(Login.id);
		userNames = users.keySet().toArray(new String[users.size()]);
		userOnlineStatus = new String[userNames.length];
		
		// Determine user status and update the screen
		for(int i=0; i<=userNames.length-1; i++) {
			
			userOnlineStatus[i] = userNames[i];  // set user status to offline.
			Log.d("UserNames" , "UsersName = " + userNames[i]);
		}
		updateScreenDisplay();
		
		// Begin screen updating thread
		screenUpdater.start();
		
		View StartButton = this.findViewById(R.id.start_button);
		StartButton.setOnClickListener(this);
		View CancelButton = this.findViewById(R.id.cancel_button);
		CancelButton.setOnClickListener(this);
	}

	/** 
	 * Thread for updating the screen 
	 */
	final Thread screenUpdater = new Thread() {
		public void run() {
			try {	
				while(execute) {
					Log.d("***" , "thread  " );
					Thread.sleep(10000);
					Log.d("***" , "thread 2 scrum " );
					updateScreenDisplay();
				}
			} catch(Exception e) {
				Log.d("EXCEPTION", e.getMessage());
			}
		}
	};

	/** 
	 * Retrieve list of stories and display them on the screen 
	 */
	private void getStorys() {
		
		id = Login.id;
		Log.d("SID", id);
	
		// Retrieve story list if it hasn't been retrieved yet 
		if(check== 0) {
			storys = GoogleService.returnStorys(id);
			details = GoogleService.returnDetails(id);
			GoogleService.putUsers(id);
			storyNames = storys.keySet().toArray(new String[storys.size()]);
			storyID = storys.values().toArray(new String[storys.size()]);
	    	detailed = details.keySet().toArray(new String[details.size()]);
			check =1;
		}
		
    	for(int i=0; i<=storyNames.length-1; i++){
			Log.d("StoryName" , "Name = " + storyNames[i]);
			}
    	
    	openSelectStoryDialog();
	}
	
	/** 
	 * Display list of stories in a dialog 
	 */
	private void openSelectStoryDialog() {
		new AlertDialog.Builder(this)
    		.setTitle(R.string.select_story_title)
    		.setItems(storyNames,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialoginterface, int i) {
						exampleAlert(detailed[i]);
				stid = i;
				Log.d("idddddddd" , "= " + stid);
					}
    		})
    		.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {	
                }
    		})
    		.show();
	}
	
	/** 
	 * Confirm story selection 
	 */
	private void exampleAlert(final String storys) {
		final String extendedStory = storys;
		new AlertDialog.Builder(this)
        .setTitle("Estimate This Story?")
        .setMessage(storys)
        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        	
                public void onClick(DialogInterface dialog, int whichButton) {
                	
                	storyId = storyID[stid];
                	Log.d("checking id " , " = " + storyId);
            		
            		String[] users = Login.usersNames;
            		Log.d("Users[0]", users[0]);
                	for(String user : userNames) {
                		if(user != users[0]) {
                			Log.d("ADMIN SENT", user);
                			sendMessageToUser(user);
                		}
                	}
                	execute = false;
                	connection.disconnect();
                	startVoting(extendedStory);
                }})
        .setNegativeButton("No", new DialogInterface.OnClickListener() {
        	
                public void onClick(DialogInterface dialog, int whichButton) {
                        openSelectStoryDialog();
                }}).show();
	}

	/** 
	 * Launch vote waiting screen 
	 */
	private void startVoting(String SelectedTitle) {
		Intent l = new Intent(this, ModeratorResultsWaitingScreen.class);
		Log.d("id", id);
		l.putExtra("SID", id);
		l.putExtra("storysList", storyNames);
		l.putExtra("selected", SelectedTitle);
		l.putExtra("details", detailed);
		l.putExtra("moderator", Login.usersNames[0]);
    	startActivity(l);
	}
	
	/** 
	 * Process button clicks 
	 */
	public void onClick(View v) {
		switch (v.getId()) {
    		case R.id.start_button:
    			getStorys();
    			break;
    		case R.id.cancel_button:
    				finish();
    			break;
		}
	}
	
	/** 
	 * Method for updating the screen 
	 */ 
	private void updateScreenDisplay() {
		setListAdapter(new ArrayAdapter<String>(this,
	    android.R.layout.simple_list_item_1, userOnlineStatus));
	}

	/**
	 * Connect to the Jabber server and send a message to a user
	 */
	private void connectToServer() {

        // Print out connection information
		Log.d("***", "Admin Host =" + connConfig.getHost());
		Log.d("***", "Admin Service Name =" + connConfig.getServiceName());
		Log.d("***", "Admin Security Mode =" + connConfig.getSecurityMode());

		try {	
			// Connect to the server and log in with user name and password
			Log.d("***", "Admin Connect...");
			connection.connect();
			connection.login("demosundog@gmail.com", "sundog101");
			Log.d("***", "Admin Connected as: " );
			connection.addPacketListener(myListener, filter);

		} catch (XMPPException e) {
			Log.d("***", "XMPPException");
		}
	}
	
	/** 
	 * Send story selection to users 
	 */
	public void sendMessageToUser(String user) {
		
		// Create a new message, set the message properties, and send the message
		Message message = new Message();
		message.setType(Message.Type.headline);
		message.setTo(user);
		message.setBody("" + scrumMaster.stid );
	    connection.sendPacket(message);
	    Log.d("***", "Admin sent message");
	}
	
	/** 
	 * Set all users' status' 
	 */
	private void setUserStatus() {
		String[] temp = User.split("/");
		User = temp[0];
		 Log.d("***", "checking Status 1");
		
		for(int i = 0; i <scrumMaster.userNames.length;i++ ) {
			Log.d("***", "checking Status 2" + User);
			
			if(User.equalsIgnoreCase(scrumMaster.userNames[i])) {
				
				scrumMaster.userOnlineStatus[i]="***"+scrumMaster.userNames[i]; // set user online status to true
				Log.d("***", "checking Status " + scrumMaster.userOnlineStatus[i]); 
			}
		}
	}
}
